package org.plex.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * 对输入的数据流进行GZIP压缩和解压的功能
 * @author 黄卫立
 */

public final class GzipUtil {

	  private  GzipUtil()
	  {};
	  
	  /**
	   * 对输入的数据进行GZIP压缩
	   * @param input
	   * @return
	   * @throws IOException
	   */
	  public static byte[] ungzip(byte[] input) throws IOException
	  {
		 //转化为字节输入流
		 ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(input);
		 
		 ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
		 //对字节输入流进行GZIP压缩
		 GZIPInputStream inputStream=new GZIPInputStream(byteArrayInputStream);
		 byte[] chrs=new byte[512];
		 int nRead=0;
		 try
		 {
			while((nRead=inputStream.read(chrs, 0, 512))!=-1)
			{
				byteArrayOutputStream.write(chrs,0,nRead);
			}
			 
		 }catch(EOFException oEOF)
		 {
			 oEOF.printStackTrace();
		 }
		 inputStream.close();
		 byteArrayInputStream.close();
		 byte[] outputbytes=byteArrayOutputStream.toByteArray();
		 byteArrayOutputStream.close();
		 return outputbytes;
	  }
	  
	  /***
	   * 对输入的数据进行GZIP解压
	   * @param input
	   * @return
	   * @throws IOException
	   */
	  public static byte[] gzip(byte[] input) throws IOException
	  {
		  ByteArrayOutputStream os=new ByteArrayOutputStream();
		  GZIPOutputStream gos=new GZIPOutputStream(os);
		  gos.write(input,0,input.length);
		  gos.close();
		  byte[] outputbytes=os.toByteArray();
		  os.close();
		  return outputbytes;	  
	  }
}
